package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.OkHttpUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private final WeChatProperties properties;

    private final OkHttpUtil okHttpUtil;

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(WeChatProperties properties, OkHttpUtil okHttpUtil, UserMapper userMapper) {
        this.properties = properties;
        this.okHttpUtil = okHttpUtil;
        this.userMapper = userMapper;
    }


    /**
     * 微信登录
     *
     * @param userLoginDTO 用户dto
     * @return 用户信息
     */
    @Override
    public User wxLogin(@NotNull UserLoginDTO userLoginDTO) {
        //调用微信接口服务获得当前用户的openid
        String openId = getOpenId(userLoginDTO.getCode());
        System.out.println(openId);
        //判断openid是否为空，如果为空抛异常
        if (!StringUtils.hasLength(openId)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        User user = userMapper.getByOpenId(openId);
        //如果是新用户，自动完成注册
        if (user == null) {
            user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户openid
     *
     * @param code code
     * @return openid
     */
    private String getOpenId(@NotNull String code) {
        String body = okHttpUtil.doGet(WX_LOGIN + "?appid=" + properties.getAppid().trim() + "&secret=" + properties.getSecret().trim() + "&js_code=" + code.trim() + "&grant_type=authorization_code");
        JSONObject jsonObject = JSON.parseObject(body);
        return jsonObject.getString("openid");
    }
}
